const { think } = require('thinkjs');
const Base = require('./base.js');
const moment = require('moment');
const { default: BigNumber } = require('bignumber.js');

module.exports = class extends Base {
  async listAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const query = this.get();
    // query.status = this.get('status') || 0;

    delete query.page;
    delete query.size;
    // aiModelSelect
    const data = await this.model('income_list')
      .where(query)
      .alias('a')
      .order(['id DESC'])
      .page(page, size)
      .countSelect();

    return this.success(data);
  }

  async zengzhiIncomeAction() {
    const query = {
      contract_id: this.get('contract_id'),
    };
    const data = await this.model('zengzhi_detail')
      .where(query)
      .order(['id DESC'])
      .select();

    const inMoney =
      (await this.model('zengzhi_detail')
        .where(Object.assign({ inout_type: 1 }, query))
        .sum('money')) || 0;

    const outMoney =
      (await this.model('zengzhi_detail')
        .where(Object.assign({ inout_type: 2 }, query))
        .sum('money')) || 0;

    const restMoney = BigNumber(inMoney)
      .minus(BigNumber(outMoney))
      .toFixed();

    for (const item of data) {
      if (item.circle_start && item.circle_end) {
        item.circle = [item.circle_start, item.circle_end];
      }
    }

    return this.success({
      data: data,
      inMoney,
      outMoney,
      restMoney,
    });
  }

  async orderIncomeAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 2000;

    const query = {
      contract_id: this.get('contract_id'),
    };
    let order = ['remind_date DESC', 'id DESC'];
    let totleMoney,
      restMoney,
      hasMoney,
      qitaMoney,
      yajinMoney,
      acList,
      acDbList,
      dianfei,
      shuifei;
    if (this.get('type')) {
      query.type = this.get('type');
      if (query.type === 'fangzu') {
        query.type = ['NOTIN', ['ruzhang', 'shuidian', 'bujiao']];
        // const c = await this.model('contract_list')
        //   .where({ id: this.get('contract_id') })
        //   .field('fangzu, wuye')
        //   .find();
        totleMoney = await this.model('income_list')
          .where({
            contract_id: this.get('contract_id'),
            type: ['IN', ['fangzu', 'wuye']],
          })
          .sum('money');

        restMoney = await this.model('income_list')
          .where({
            contract_id: this.get('contract_id'),
            type: ['IN', ['fangzu', 'wuye']],
            status: 0,
          })
          .sum('money');
        // hasMoney = await this.model('income_list')
        //   .where({
        //     contract_id: this.get('contract_id'),
        //     type: 'fangzu',
        //     status: 1,
        //   })
        //   .sum('money');
        yajinMoney = await this.model('income_list')
          .where({
            contract_id: this.get('contract_id'),
            type: 'yajin',
          })
          .sum('money');

        qitaMoney = await this.model('income_list')
          .where({
            contract_id: this.get('contract_id'),
            type: 'qita',
          })
          .sum('money');
      }

      if (query.type === 'shuidian') {
        const acInfo = await this.model('contract_list')
          .where({ id: query.contract_id })
          .field('ac_list, dianbiao_list')
          .find();
        if (acInfo.ac_list) {
          acList = await this.model('equipment_list')
            .where({ id: ['IN', acInfo.ac_list] })
            .select();
        }
        if (acInfo.dianbiao_list) {
          acDbList = await this.model('ac_db')
            .where({ id: ['IN', acInfo.dianbiao_list] })
            .select();
        }

        const concat = await this.model('contract_list')
          .where({ id: query.contract_id })
          .field('dianfei, shuifei')
          .find();
        dianfei = concat.dianfei;
        shuifei = concat.shuifei;

        order = ['circle_start DESC'];
      }
    }

    const data = await this.model('income_list')
      .where(query)
      .order(order)
      .page(page, size)
      .countSelect();

    for (const item of data.data) {
      if (item.type === 'yajin') {
        item.type = item.yajin_type;
      }
      if (item.circle_start && item.circle_end) {
        item.circle = [item.circle_start, item.circle_end];
      }
      if (item.type === 'shuidian') {
        if (item.shuidian_info) {
          item.shuidianInfo = JSON.parse(item.shuidian_info);
          item.shuidian_info_0 = item.shuidianInfo.ac_name;
          item.shuidian_info_1 = item.shuidianInfo.prev;
          item.shuidian_info_2 = item.shuidianInfo.current;
        }
      }
    }
    Object.assign(data, {
      totleMoney,
      restMoney,
      acList,
      acDbList,
      yajinMoney,
      qitaMoney,
      dianfei,
      shuifei,
    });

    return this.success(data);
  }

  async updateAction() {
    const values = this.post();
    const id = this.post('id');
    const model = this.model('income_list');
    delete values.id;
    await model.where({ id: id }).update(values);

    return this.success(values);
  }

  async putZengzhiAction() {
    const values = this.post();
    const id = this.post('id');
    if (values.update_time === '') {
      delete values.update_time;
    }
    if (values.account_id === '') {
      delete values.account_id;
    }
    if (id > 0) {
      await this.model('zengzhi_detail')
        .where({ id: id })
        .update(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '编辑增值收入',
        content: id,
        type: values.type,
      });
    } else {
      delete values.id;

      values.create_time = ['exp', 'CURRENT_TIMESTAMP()'];

      const addId = await this.model('zengzhi_detail').add(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '新增增值收入',
        content: addId,
        type: values.type,
      });
    }
    return this.success(values);
  }

  async putIncomeAction() {
    const values = this.post();
    const id = this.post('id');
    if (values.month) {
      values.year = moment(values.month).year();
      values.month = moment(values.month).month() + 1;
    }

    if (values.circle && values.circle.length) {
      values.circle_start = values.circle[0];
      values.circle_end = values.circle[1];
    }

    if (values.update_time === '') {
      delete values.update_time;
    }

    if (values.account_id === '') {
      delete values.account_id;
    }

    if (values.type === 'yajinShuidian') {
      values.type = 'yajin';
      values.yajin_type_str = '水电押金';
      values.yajin_type = 'yajinShuidian';
    } else if (values.type === 'yajinZhuangxiu') {
      values.type = 'yajin';
      values.yajin_type = 'yajinZhuangxiu';
      values.yajin_type_str = '装修押金';
    } else if (values.type === 'yajin') {
      values.yajin_type = 'yajin';
      values.yajin_type_str = '租赁押金';
    }

    if (id > 0) {
      await this.model('income_list')
        .where({ id: id })
        .update(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '编辑帐目收入',
        content: id,
        type: values.type,
      });
    } else {
      delete values.id;

      values.create_time = ['exp', 'CURRENT_TIMESTAMP()'];

      const addId = await this.model('income_list').add(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '新增帐目收入',
        content: addId,
        type: values.type,
      });
    }
    return this.success(values);
  }

  async delIncomeAction() {
    const id = this.get('id');
    const d = await this.model('income_list')
      .where({ id: id })
      .find();
    await this.model('income_list')
      .where({ id: id })
      .limit(1)
      .delete();
    this.model('addLog').add({
      user_id: this.getLoginUserId(),
      title: '删除帐目收入',
      content: JSON.stringify(d),
    });

    return this.success();
  }

  async delZengzhiAction() {
    const id = this.get('id');
    const d = await this.model('zengzhi_detail')
      .where({ id: id })
      .find();
    await this.model('zengzhi_detail')
      .where({ id: id })
      .limit(1)
      .delete();
    this.model('addLog').add({
      user_id: this.getLoginUserId(),
      title: '删除增值收入',
      content: JSON.stringify(d),
    });

    return this.success();
  }

  async recordAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    let query;
    if (this.get('getType') == 2) {
      query = {
        status: 0,
      };
    }
    const data = await this.model('income_list')
      .where(query)
      .alias('a')
      .order(['id DESC'])
      .page(page, size)
      .countSelect();

    return this.success(data);
  }

  async yajinAction() {
    const id = this.get('id');
    let data = await this.model('income_list')
      .where({ contract_id: id, type: ['IN', ['yajin', 'bujiao', 'ruzhang']] })
      .order(['id DESC'])
      .select();

    for (const item of data) {
      if (item.type === 'bujiao') {
        item.status = 3;
      } else if (item.type === 'ruzhang') {
        item.status = 4;
      }
    }

    const data2 = await this.model('output_list')
      .where({ contract_id: id, type: 'tuifei' })
      .order(['id DESC'])
      .select();

    for (const item of data2) {
      item.yajin_type = '退费';
      item.status = 2;
    }

    data = data.concat(data2);

    return this.success(data);
  }
  async yajinUpdateAction() {
    const id = this.get('id');
    const status = this.get('status');
    if (think.isEmpty(status) || status === '0') {
      const data = await this.model('income_list')
        .where({ id: id })
        .update({
          status: 2,
        });

      return this.success(data);
    } else {
      const data = await this.model('income_list')
        .where({ id: id })
        .update({
          status: 1,
          type: 'ruzhang',
        });

      return this.success(data);
    }
  }

  async putBackAction() {
    const values = this.post();
    if (values.backStatus === 1) {
      await this.model('income_list').add({
        update_time: values.update_time,
        money: values.money,
        remark: values.remark,
        account_id: values.account_id,
        type: 'bujiao',
        yajin_type: '补缴',
        yajin_type_str: '补缴',
        create_time: ['exp', 'CURRENT_TIMESTAMP()'],
        contract_id: values.contract_id,
      });
    } else if (values.backStatus === 2) {
      await this.model('output_list').add({
        update_time: values.update_time,
        money: values.money,
        remark: values.remark,
        account_id: values.account_id,
        type: 'tuifei',
        yajin_type: '退费',
        yajin_type_str: '退费',
        create_time: ['exp', 'CURRENT_TIMESTAMP()'],
        contract_id: values.contract_id,
      });
    }
    return this.success();
  }
};
